<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/*
 * Smarty {twit_fri_time} plugin
 *
 * File:     function.twit_fri_time.php
 * Type:     function
 * Name:     twit_fri_time
 * Purpose:  twitter friends_timeline.rss get output
 *
 * @link   http://php.iklv.net/google_code/ {twit_use_time}
 * @author Isam Nagoya <2fast2@live.jp>
 * @param  array Format:
 * <pre>
 * array(
 *     'count'  => output tweet num,
 *     'encode' => output source code
 * );
 * </pre>
 * @param  object Smarty
 * <code>
 * {twit_fri_time}
 * {twit_fri_time encode="EUC-JP"}
 * {twit_fri_time count=10}
 * {twit_fri_time count=10 encode="EUC-JP"}
 * </code>
 *
 */
function smarty_function_twit_fri_time($params,  &$smarty) {
    $rest_uri = "http://twitter.com/statuses/friends_timeline.rss";
    $up = isset($params["up"]) ? trim($params["up"]) : "";
    if(!$up) {
        $smarty->trigger_error("twit_fri_time: missing up parameter");
    }
    $result = @file_get_contents($rest_uri , false, stream_context_create(array(
        "http" => array(
            "method"  => "GET",
            "header" => "Authorization: Basic ". $up,
            "timeout" => 15
         )
    )));

    if($result) {
        $xml = simplexml_load_string($result);
        $i   = 1;
        $encode = isset($params["encode"]) ? trim($params["encode"]) : mb_internal_encoding();
        $data = '<div class="friend_time">';
        foreach($xml->channel->item as $val) {
            $data .= '<div class="friend_time_item">';
            $data .= mb_convert_encoding($val->description, $encode, mb_detect_order());
            $data .= "</div>";
            $i++;
            if(isset($params["count"])) {
                if($i > $params["count"]) {
                    break;
                }
            }
        }
        $data .= '</div>';
        return $data;
    }else{
        $smarty->trigger_error("twit_use_time: no response");
    }
}
